//
//  BKL_CycelScrollView.m
//  BKLMedicalCare
//
//  Created by ma c on 2017/6/15.
//  Copyright © 2017年 q mac. All rights reserved.
//

#import "BKL_CycelScrollView.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>

@interface BKL_CycelCell : UICollectionViewCell
- (void)fillData:(id)data;
@end
@implementation BKL_CycelCell
{
    UIImageView *_imageView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    _imageView = [[UIImageView alloc] init];
    _imageView.contentMode = UIViewContentModeScaleToFill;
    [self.contentView addSubview:_imageView];
    
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

- (void)fillData:(id)data {
    if (!data) {
        return;
    }
    NSString *imageUrlString = data[@"imageUrl"];
    UIImage *placeholderImage = data[@"placeholderImage"];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:imageUrlString] placeholderImage:placeholderImage];
}

@end

@interface BKL_CycelScrollView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (nonatomic, weak)UIPageControl *pageControl;
@property (nonatomic, weak)UICollectionView *collectionView;
@property (nonatomic, weak)NSTimer *timer;
@end

@implementation BKL_CycelScrollView
NSString *const bkl_cycelCellIdentifier = @"bkl_cycelCellIdentifier";
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    
    _images = [NSArray array];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [collectionView registerClass:[BKL_CycelCell class] forCellWithReuseIdentifier:bkl_cycelCellIdentifier];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = YES;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.bounces = NO;
    collectionView.backgroundColor = [UIColor lightGrayColor];
    _collectionView = collectionView;
    [self addSubview:_collectionView];
    
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    pageControl.userInteractionEnabled = NO;
    _pageControl = pageControl;
    [self addSubview:_pageControl];
    
    [self makeConstraints];
}

- (void)makeConstraints {
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.mas_right).offset(-10);
        make.bottom.mas_equalTo(self.mas_bottom);
    }];
}

- (void)scrollBegin {
    [self setupTimer];
}

- (void)scrollEnd {
    [self invalidateTimer];
}
// timer
- (void)setupTimer {
    if (_timer) {
        [self invalidateTimer];
    }
    NSTimer *timer = [NSTimer timerWithTimeInterval:4.0 target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
    _timer = timer;
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)invalidateTimer
{
    [_timer invalidate];
    _timer = nil;
}

// 数据处理
- (void)setImages:(NSArray<NSString *> *)images {
    if (images.count == 1) {
        _images = images.copy;
        _pageControl.numberOfPages = 0;
        [self invalidateTimer];
        [_collectionView reloadData];
        return;
    }
    // 首尾各加上一张图片
    NSMutableArray *array = images.mutableCopy;
    [array insertObject:images.lastObject atIndex:0];
    [array addObject:images.firstObject];
    _images = array.copy;
    [self setupTimer];
    _pageControl.numberOfPages = _images.count - 2;
    [_collectionView reloadData];
    _pageControl.currentPage = [self currentPageIndex];
}

- (NSInteger)currentIndex {
    // 只支持横向
    NSInteger index = 0;
    index = (_collectionView.contentOffset.x + _collectionView.frame.size.width * 0.5) / _collectionView.frame.size.width;
    return index;
}

- (NSInteger)currentPageIndex {
    return [self currentIndex] - 1;
}

// timer action

- (void)automaticScroll {
    if (_images.count == 1) {
        return;
    }
    NSInteger index = [self currentIndex];
    index++;
    [self scrollToIndex:index];
}

- (void)scrollToIndex:(NSInteger)index {
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}

#pragma mark - collection delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BKL_CycelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bkl_cycelCellIdentifier forIndexPath:indexPath];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.frame.size;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    BKL_CycelCell *bklCell = (BKL_CycelCell *)cell;
    [bklCell fillData:@{@"imageUrl" : _images[indexPath.row], @"placeholderImage" : _placehoderImage==nil?[[UIImage alloc] init]:_placehoderImage}];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 点击
    NSLog(@"tttttouch");
}

#pragma mark scroll delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self invalidateTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self setupTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentIndex = [self currentIndex];
    if (currentIndex == 0) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_images.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    else if(currentIndex == _images.count - 1) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    currentIndex = [self currentIndex];
    _pageControl.currentPage = [self currentPageIndex];
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    NSInteger currentIndex = [self currentIndex];
    if (currentIndex == 0) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_images.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    else if(currentIndex == _images.count - 1) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = [self currentPageIndex];
}

@end
